<template>
  <div class="wrap moniter-table" @scroll="handleScroll">
    <div class="tips" v-if="$store.state.session.user.type === 'agent'">{{$t('monitor.tips')}}</div>
    <affix :label="$t('monitor.multiChannelMonitorList')" :moniterFlag="'multiChannel'" :monitor="true" :showFlag="multiChannelFl" @open="open" style="margin-top: 36px;">
      <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0" v-show="multiChannelFl">
        <thead>
        <tr>
          <th><div class="cell" v-once>{{$t('report.imAccessId')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.sessionNumToday')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.sessionNumTodayGet')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.sessionNumTodayAnswer')}}</div></th>
        </tr>
        </thead>
        <tbody class="el-table__body">
        <tr-common  v-for="one in multiChannel" :key="one._id" :one="one" :header="header.multiChannel"></tr-common>
        </tbody>
      </table>
    </affix>
    <affix :label="$t('monitor.multiChannelSkillMonitorList')" :moniterFlag="'multiChannelSkill'" :monitor="true" :showFlag="multiChannelSkillFl" @open="open">
      <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0" v-show="multiChannelSkillFl">
        <thead>
        <tr>
          <th><div class="cell" v-once>{{$t('monitor.skillGroupName')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.openAutoReceiveAgent')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.checkInAgent')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.waitingSessionNum')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.connectSessionNum')}}</div></th>
        </tr>
        </thead>
        <tbody class="el-table__body">
        <tr-common  v-for="one in multiChannelSkill" :key="one._id" :one="one" :header="header.multiChannelSkill"></tr-common>
        </tbody>
      </table>
    </affix>
    <affix :label="$t('monitor.agentMonitorList')" :monitor="true" :moniterFlag="'agent'" :showFlag="agentFl" @open="open">

      <div class="Seats" v-show="agentFl">
        <el-row class="agnet-search">
          <el-col :span="1" class="search-label">{{$t('public.queues')}}：</el-col>
          <el-col :span="4">
            <el-select size="mini" v-model="queue" :placeholder="$t('public.pleasePick')" @change="queueSearch" filterable collapse-tags :multiple="true" class="select-width" clearable>
              <el-option
                v-for="item in allQueue"
                :label="item.DisplayName"
                :key="item._id"
                :value="item._id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="1" class="search-label">{{$t('public.agent')}}：</el-col>
          <el-col :span="5">
            <el-select size="mini" v-model="agent" :placeholder="$t('public.pleasePick')" @change="monitorSearch" filterable collapse-tags :multiple="true" class="select-width" clearable>
              <el-option
                      v-for="item in allAgent"
                      :label="item.displayName + '['+ item.exten + ']'"
                      :key="item._id"
                      :value="item._id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <div class="checkbox-wrap">
              <el-checkbox v-model="includeSubordinate" @change="monitorSearch">{{$t('public.includeSubordinate')}}</el-checkbox>
            </div>
          </el-col>
          <div class="clear10"></div>
        </el-row >
        <el-row>
          <el-col :span="21">
            <div class="config" v-if="configHeaderShow">
              <i class="iconfont icon-peizhi"></i><span class="tex" @click="config">{{$t('monitor.setHeaderConfig')}}</span>
            </div>&nbsp;
          </el-col>
          <el-col :span="3">
            <p class="search-label record-num">
              {{$t('monitor.totalRecord', {count: agentCount})}}
            </p>
          </el-col>
          <div class="clear10"></div>
        </el-row>
        <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0">
          <thead>
            <tr>
              <th v-for="item in headOptionsNoShow" :key="item.name" :class="{ ascending: (item.name === sortObj.name)&&(sortObj.type === 'up'),descending: (item.name === sortObj.name)&&(sortObj.type === 'down') }"><div class="cell" @click.stop="sort(item.name)">{{item.displayname}}<span class="caret-wrapper" v-if="item.name !== 'answerStyle'" ><i class="sort-caret ascending"></i><i class="sort-caret descending"></i></span></div></th>
              <th v-for="item in monitorHeader" :key="item.name" v-show="item.show === true" :class="{ ascending: (item.name === sortObj.name)&&(sortObj.type === 'up'),descending: (item.name === sortObj.name)&&(sortObj.type === 'down') }"><div class="cell" @click="sort(item.name)">{{item.displayname}}<span class="caret-wrapper"><i class="sort-caret ascending"></i><i class="sort-caret descending"></i></span></div></th>
            </tr>
          </thead>
          <!-- <tbody class="el-table__body" ref="agent"></tbody> -->
          <RenderFilter class="el-table__body" ref="agent" :minAndMax="minAndMax" :length="monitorPeerDisplayShow.length">
            <tr-agent-im
              :one="one"
              v-for="(one, i) in monitorPeerDisplayShow"
              :show-index="i"
              :key="one.userId"
              :monitorHeader="monitorHeader"
              v-show="one.isShow"
            ></tr-agent-im>
          </RenderFilter>
        </table>
      </div>
    </affix>
    <header-option :show="isShow" :option="headOptionsShow"  :noDrag="headOptionsNoShow" type="im_monitor_agent_multi" v-on:close="close"></header-option>
  </div>
</template>
<script>
//  let todayIncoming = $t('monitor.todayIncoming')
  import {deepClone, getCache, getCacheByKey} from '@/utils/m7Utils.js'
  import {showCountDown} from '@/utils/workflowUtils.js'
  import {imMonitorGetQueueAutoClaimAgents, renderAutoClaimDispaly, imMonitorGetQueueAgents} from '@/utils/monitor.js'
  import headerOption from '../report/base/headerOption.vue'
  import affix from './../../ui-modules/affix/Affix.vue'
  import trAgentIm from './TrAgentIm.vue'
  import trCommon from './TrCommon.vue'
  import RenderFilter from './RenderFilter.vue'

  export default {
    name: 'monitorTableIm',
    data () {
      return {
        isMounted: false,
        showFlag: true,
        multiChannelFl: true,
        multiChannelSkillFl: true,
        agentFl: true,
        agent: [],
        queue: [],
        agentArray: [], // 显示的坐席
        allAgent: [],
        allQueue: [],
        includeSubordinate: false,
        monitorPeerDisplay: [],
        monitorPeerDisplayShow: [],
        timer: '',
        isShow: false,
        headOptionsShow: {},
        scope: 'noScope',
        headOptionsNoShow: [{'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true}, {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}],
        agentCount: 0,
        sortObj: {
          name: '',
          type: '',
          num: 0
        },
        header: {
          multiChannel: [{prop: 'name'}, {prop: 'newSession'}, {prop: 'accessSession'}, {prop: 'closeSession'}],
          multiChannelSkill: [{prop: 'DisplayName'}, {prop: 'autoClaimDisplay', tooltip: true}, {prop: 'checkInAgent', tooltip: true}, {prop: 'waitClaim', color: 'red'}, {prop: 'manualSession'}]
        },
        monitorHeader: [],
        minAndMax: {
          min: 0,
          max: 30
        }
      }
    },
    inject: ['configHeaderShow'],
    computed: {
      currentAgentState () {
        return this.$store.state.monitor.agentStateChangeIm.random
      },
      multiChannel () {
        let data = this.$store.state.monitor.table.MultiChannel
        let array = []
        if (this.isMounted) {
          for (var i in data) {
            let one = data[i] || {}
            array.push({_id: one._id, name: one.name, newSession: one.newSession, accessSession: one.accessSession, closeSession: one.closeSession})
          }
        }
        return array
      },
      multiChannelSkill () {
        let data = this.$store.state.monitor.table.MultiChannelSkill
        let array = []
        if (this.isMounted) {
          for (var i in data) {
            let item = {}
            item.DisplayName = data[i].DisplayName
            item.manualSession = data[i].manualSession
            item.waitClaim = data[i].waitClaim
            item.checkInAgent = imMonitorGetQueueAgents(data[i])
            item.autoClaimDisplay = imMonitorGetQueueAutoClaimAgents(data[i])
            item._id = data[i]._id
            array.push(item)
          }
        }
        return array
      }
    },
    components: {
      headerOption,
      affix,
      trAgentIm,
      trCommon,
      RenderFilter
    },
    watch: {
      currentAgentState (newValue) {
        let im = this.$store.state.monitor.table.agentMonitor
        let newV = this.$store.state.monitor.agentStateChangeIm.userId
        if (this.scope === 'noScope') {
        } else {
          if (this.scope.indexOf(newV) === -1) {
            return
          }
        }
        let index = -1
        for (let i = 0; i < this.monitorPeerDisplay.length; i++) {
          if (this.monitorPeerDisplay[i].userId === newV) {
            index = i
            break
          } else {
            index = -1
          }
        }
        if (index === -1) {
        } else {
          let data = this.monitorPeerNew(im[newV], 'update', newV)
          let oldShow = this.monitorPeerDisplay[index].isShow
          let newShow = this.filterAgent(data)
          if (oldShow === newShow) {
            data.isShow = oldShow
          } else if (newShow) {
            data.isShow = newShow
            this.agentCount++
          } else {
            data.isShow = newShow
            this.agentCount--
          }
          // this.monitorPeerDisplay.splice(index, 1, data)
          this.update(this.monitorPeerDisplay[index], data)
        }
      }
    },
    methods: {
      handleScroll () {
        if (this.$refs.agent && this.$refs.agent.$el) {
          let clientRect = this.$refs.agent.$el.getBoundingClientRect()
          let top = -clientRect.top

          console.log(top)
          let min = ~~(top / 51)
          if (min < 0) {
            min = 0
          }
          let max = min + 30

          this.minAndMax.min = min
          this.minAndMax.max = max
        }
      },
      update (target, data) {
        for (const key in data) {
          if (key in target) {
            target[key] = data[key]
          } else {
            this.$set(target, key, data[key])
          }
        }
      },
      open (data) {
        if (data.moniterFlag === 'call') {
          this.callFl = data.flag
        } else if (data.moniterFlag === 'multiChannel') {
          this.multiChannelFl = data.flag
        } else if (data.moniterFlag === 'callSkill') {
          this.callSkillFl = data.flag
        } else if (data.moniterFlag === 'multiChannelSkill') {
          this.multiChannelSkillFl = data.flag
        } else if (data.moniterFlag === 'outCall') {
          this.outCallFl = data.flag
        } else if (data.moniterFlag === 'agent') {
          this.agentFl = data.flag
        }
      },
      filterAgent (item) {
        // 座席条件
        let filter1 = false
        if (this.agentArray.indexOf(item.userId) !== -1) {
          filter1 = true
        }
        return filter1
      },
      queueSearch (value) {
        let data = this.queue
        //        先用promise.all 将所有的peer.AssignMembers 集合进arrayList  ,再遍历arrayList发送异步请求，再次使用promise.all 将所有的resp写入agents 待.all完成后，agents就是完整的，进行去重
        let arrayList = []
        this.agent = []
        this.allAgent = []
        if (data.length !== 0) {
          // 先用promise把所有的AssignMembers写入arrayList
          data.map((item) => {
            let peer = getCacheByKey('mailQueues', '_id', item)
            let AssignMembers = peer.AssignMembers || []
            for (let i = 0; i < AssignMembers.length; i++) {
              let one = AssignMembers[i]
              if (arrayList.indexOf(one.agentID) === -1) {
                arrayList.push(one.agentID)
              }
            }
          })
          arrayList.forEach((item2) => {
            let all = this.$agentsMap() || {}
            let agent = all[item2] || ''
            if (agent) {
              this.allAgent.push({ displayName: agent.displayName, exten: agent.exten, _id: agent._id, parentId: agent.parentId })
            }
          })
        } else {
          let agents = getCache('agents') || []
          // 筛选出未停用座席
          this.allAgent = agents.filter((item) => {
            if (item.status !== 'disable') {
              return true
            } else {
              return false
            }
          })
        }
        this.monitorSearch()
      },
      monitorSearch () {
        this.agentArray = this.change(this.agent)
        this.agentCount = 0
        this.monitorPeerDisplayShow = []

        for (let i in this.monitorPeerDisplay) {
          if (this.filterAgent(this.monitorPeerDisplay[i])) {
            this.monitorPeerDisplay[i].isShow = true
            this.agentCount++
            this.monitorPeerDisplayShow.push(this.monitorPeerDisplay[i])
          } else {
            this.monitorPeerDisplay[i].isShow = false
          }
        }
      },
      scopeAgents () {
        let session = this.$store.state.session
        if (session.user.type !== 'admin' && session.user.scope.chat !== 'all') {
          let lowUsers = session.user.moduleUsers.chat || []
          return lowUsers
        } else {
          return 'noScope'
        }
      },
      sort (name) {
        if (this.sortObj.name !== name) {
          this.sortObj.num = 0
        }
        this.sortObj.name = name
        if (this.sortObj.num % 2) {
          this.sortObj.type = 'down'
        } else {
          this.sortObj.type = 'up'
        }
        this.sortObj.num++
        this.monitorPeerDisplay.sort((a, b) => {
          if (this.sortObj.type === 'down') {
            return this.sortMethod(a, b, this.sortObj.name)
          } else {
            return this.sortMethod(b, a, this.sortObj.name)
          }
        })

        this.monitorPeerDisplayShow.sort((a, b) => {
          if (this.sortObj.type === 'down') {
            return this.sortMethod(a, b, this.sortObj.name)
          } else {
            return this.sortMethod(b, a, this.sortObj.name)
          }
        })
      },
      sortMethod (a, b, name, type) {
        let x = a[name]
        let y = b[name]
        if (name === 'mobileClaimTime' || name === 'pcClaimTime' || name === 'pcState' || name === 'agentName' || name === 'mobileState' || name === 'mobileAutoStatus' || name === 'pcAutoStatus' || name === 'mailAutoStatus') {
          return x.localeCompare(y)
        } else {
          return x - y
        }
      },
      change (selectAgent) {
        var agents = []
        let agentList = this.allAgent
        if (selectAgent.length === 0) {
          this.allAgent.forEach(function (item) {
            agents.push(item._id)
          })
        } else {
          agents = deepClone(selectAgent)
        }
        if (this.includeSubordinate) {
          let getAgent = function (pid) {
            for (var i = 0; i < agentList.length; i++) {
              var obj = agentList[i]
              if (obj.parentId && obj.parentId === pid && agents.indexOf(obj._id) === -1) {
                agents.push(obj._id)
                getAgent(obj._id)
              }
            }
          }
          agents.map((item) => {
            getAgent(item)
          })
        }
        return agents
      },
      monitorPeerNew (im, flag, user) {
        let item = im
        let agentName = item.displayName ? item.displayName : ''
        // userId取key值，防止两个座席绑定同一个sipNum时，一直push的问题
        let userId = user
        let agentNo = item.exten
        let pcState = item.pcState ? this.$t('monitor.online') : this.$t('monitor.offline')
        let mobileState = item.mobileState ? this.$t('monitor.online') : this.$t('monitor.offline')
        let pcAutoStatus = item.pcAutoClaim ? this.$t('public.open') : this.$t('public.close')
        let mobileAutoStatus = item.mobileAutoClaim ? this.$t('public.open') : this.$t('public.close')
        let mobileClaimTimeNum = ''
        let mobileClaimTime = ''
        let currtenTime = new Date().getTime()
        if (item.mobileClaimTime) {
          mobileClaimTimeNum = currtenTime - item.mobileClaimTime
          mobileClaimTime = showCountDown(mobileClaimTimeNum)
        }
        let pcClaimTimeNum = ''
        let pcClaimTime = ''
        if (item.pcClaimTime) {
          pcClaimTimeNum = currtenTime - item.pcClaimTime
          pcClaimTime = showCountDown(pcClaimTimeNum)
        }
//        let autoStatus = this.$t(renderAutoClaimDispaly(item.autoClaim))
        let imDealCount = item.imDealCount || ''
        let currentSessionCount = item.dealing ? item.dealing : 0
        let sessionAccessCount = item.claim ? item.claim : 0
        let sessionRollInCount = item.sessionRollInCount ? item.sessionRollInCount : 0
        let sessionRollOutCount = item.sessionRollOutCount ? item.sessionRollOutCount : 0
        let sessionCompleteCount = item.sessionCompleteCount ? item.sessionCompleteCount : 0
        let agentInviteCount = item.agentInviteCount ? item.agentInviteCount : 0
        let inviteSessionCount = item.invitsession ? item.invitsession : 0
        let mailAutoStatus = this.$t(renderAutoClaimDispaly(item.mailAutoClaim))
        return {userId: userId, agentName, agentNo, pcState, mobileState, pcAutoStatus, mobileAutoStatus, pcClaimTime, mobileClaimTime, imDealCount, sessionRollInCount, sessionRollOutCount, sessionCompleteCount, agentInviteCount, mobileClaimTimeNum, sessionAccessCount, inviteSessionCount, pcClaimTimeNum, currentSessionCount, mailAutoStatus}
      },
      timeChange () {
        let self = this
        this.timer = window.setInterval(function () {
          for (let i = 0; i < self.monitorPeerDisplay.length; i++) {
            if (self.monitorPeerDisplay[i].pcClaimTimeNum !== '') {
              self.monitorPeerDisplay[i].pcClaimTime = showCountDown(self.monitorPeerDisplay[i].pcClaimTimeNum += 1000)
            }
            if (self.monitorPeerDisplay[i].mobileClaimTimeNum !== '') {
              self.monitorPeerDisplay[i].mobileClaimTime = showCountDown(self.monitorPeerDisplay[i].mobileClaimTimeNum += 1000)
            }
          }
        }, 1000)
      },
      config () {
        this.$store.dispatch('getReportTableHeader', 'im_monitor_agent_multi').then((res) => {
          res.Config.splice(0, 2)
          this.headOptionsShow = res
          this.isShow = !this.isShow
        })
      },
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.$store.dispatch('getReportTableHeader', 'im_monitor_agent_multi').then((res) => {
            res.Config.splice(0, 2)
            this.monitorHeader = res.Config
          })
        }
      },
      fetchData () {
        let im = this.$store.state.monitor.table.agentMonitor
        this.monitorPeerDisplay = []
        // 取数据权限
        this.scope = this.scopeAgents()
        for (var n in im) {
          if (this.scope === 'noScope') {
            // this.monitorPeerDisplay.push(this.monitorPeerNew(im[n], 'create', n))
            this.$set(this.monitorPeerDisplay, this.monitorPeerDisplay.length, this.monitorPeerNew(im[n], 'create', n))
          } else {
            if (this.scope.indexOf(n) !== -1) {
              // this.monitorPeerDisplay.push(this.monitorPeerNew(im[n], 'create', n))
              this.$set(this.monitorPeerDisplay, this.monitorPeerDisplay.length, this.monitorPeerNew(im[n], 'create', n))
            }
          }
        }
        this.monitorSearch()
      }
    },
    deactivated () {
      this.minAndMax.min = 0
      this.minAndMax.max = 30
    },
    mounted () {
      if (this.$store.state.monitor.moduleOpen.webchat) {
        this.isMounted = true
        this.fetchData()
        this.timeChange()
      } else {
        this.$store.commit('monitor/MONITOR_MODULE_OPEN', {type: 'webchat', status: true})
        let p1 = this.$store.dispatch('imMonitorInit', {})
        let p2 = this.$store.dispatch('getCache', {type: 'mailQueues'})
        let p3 = this.$store.dispatch('getCache', {type: 'onlineChannelAgent'})
        Promise.all([p1, p2, p3]).then(([res1, res2]) => {
          this.isMounted = true
          this.allQueue = res2
          this.fetchData()
          this.timeChange()
        })
      }
    },
    beforeMount () {
      let agents = getCache('agents') || []
      // 筛选出未停用座席
      this.allAgent = agents.filter((item) => {
        if (item.status !== 'disable') {
          return true
        } else {
          return false
        }
      })
      this.close('save')
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .wrap
    height 100%
    padding 0 15px 50px
    box-sizing border-box
    overflow auto
    .con
      width 100%
      margin 0 auto
      .el-table
        width 100%
    .Seats
      margin 0 auto
      .el-table
        width 100%
        overflow visible
      .el-row
        border 1px solid #dedede
        border-bottom none
        padding 8px 0 0 20px
        line-height 24px
      .agnet-search
        border none
    .tip
      height 48px
      border 1px solid #dedede
      border-bottom none
      padding-left 20px
      line-height 48px
      .concurrent-num
        display inline-block
        width 20px
        height 20px
        background #7cccd3
        text-align center
        line-height 20px
        margin-left 8px
        border-radius 10px
  .el-table
    width 100%
    margin 0 auto
    td
      .cell
        color $cf-gray2
  .checkbox-wrap
    padding 4px 0 0 10px
  .search-label
    padding 4px 0px 0 0
  .record-num
    line-height 24px
    padding-right 20px
    text-align right
  .config
    padding 6px 0 0 0
    display inline-block
    .tex
      margin-left 10px
      position relative
      top -2px
      cursor pointer
      &:hover
        color $c-main
    .iconfont
      fontSize 18px
      color $c-main
  .title
      color $cf-gray0
      margin 28px 0 18px 0
      font-weight normal
      position relative
      .sign
        position relative
        width 12px
        height 12px
        background #7ccdd1
        display inline-block
        z-index 3
      .text
        position relative
        display inline-block
        padding 0 8px 0 10px
        background $cf-white
        z-index 3
      &:after
        content ""
        display inline-block
        width 100%
        left 0
        border-bottom 1px dashed $cf-level4
        position absolute
        top 12px
  .phone-state
    position relative
  .moniter-dialog
    padding 10px
    .dialog-title
      font-size 14px
      padding 15px 0
  tbody
    td
      padding-left 18px
      padding-right 18px
  .tips
    padding-top 20px
    color $c-prompt
</style>
